import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import Input from '@/components/Input';
import { useFormik } from 'formik';
// 有些第三方包，没有设置export default，下方相当于把所有的export 合并为一个对象Yup
import * as Yup from 'yup';
import { useDispatch } from 'react-redux';
import { Toast } from 'antd-mobile';
import { sendCodesAction, loginAction } from '@/store/action/user';
import { useEffect, useRef, useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { LocationStateType } from '@/components/AuthRoute';

export default function Login() {
  const history = useHistory();
  const location = useLocation<LocationStateType>();

  const formik = useFormik({
    initialValues: {
      mobile: '13719999999',
      code: '',
    },
    onSubmit: async (values) => {
      await dispatch(loginAction(values));
      Toast.show({ content: '登录成功' });
      const { state = {} as LocationStateType } = location;
      const { fromPath = '/' } = state;

      history.replace(fromPath);
    },

    validationSchema: Yup.object().shape({
      mobile: Yup.string()
        .required('手机号码不能为空')
        .matches(/^1[3-9]\d{9}$/, '请输入正确的手机号'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '请输入6位验证码'),
    }),
  });

  const [second, setSecond] = useState(0);

  const timerIdRef = useRef<number>();
  useEffect(() => {
    return () => {
      clearInterval(timerIdRef.current);
    };
  }, []);

  const dispatch = useDispatch();
  const handleSendCode = () => {
    if (formik.errors.mobile) return;
    dispatch(sendCodesAction(formik.values.mobile));
    setSecond(60);

    timerIdRef.current = window.setInterval(() => {
      setSecond((preSecond) => {
        if (preSecond === 1) {
          clearInterval(timerIdRef.current);
        }
        return preSecond - 1;
      });
    }, 1000);
  };

  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          <Input
            autoFocus
            placeholder="请输入手机号"
            autoComplete="off"
            type="text"
            name="mobile"
            maxLength={11}
            errorMsg={formik.touched.mobile ? formik.errors.mobile : ''}
            value={formik.values.mobile}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />

          <Input
            placeholder="请输入验证码"
            autoComplete="off"
            type="text"
            name="code"
            maxLength={6}
            errorMsg={formik.touched.code ? formik.errors.code : ''}
            extra={
              second === 0 ? (
                <span onClick={handleSendCode}>获取验证码</span>
              ) : (
                `${second}秒后获取`
              )
            }
            value={formik.values.code}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />

          <button
            type="submit"
            className="login-btn"
            disabled={!formik.isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
